package xiaoa.java.lucene.analyzer.mgr;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;

import xiaoa.java.lucene.analyzer.cfg.DefaultConfig;
import xiaoa.java.lucene.analyzer.core.CJKSegmenter;
import xiaoa.java.lucene.analyzer.dic.Dictionary;
import xiaoa.java.lucene.analyzer.lucene.IKAnalyzer;

/**
 * 分词工具
 * @author xiaoa
 * @date 2018年1月2日 下午10:40:04
 * @version V1.0
 *
 */
public class AnalysiWordMgr{
	
	Dictionary  dic = null;
	
	DefaultConfig config = null;
	
	public AnalysiWordMgr(){
	
		config = new  DefaultConfig();
		config.setUseSmart(true);
		// 词典管理器
		 dic = new Dictionary(config);
		
		
	}
	
	/**
	 * 添加基础词
	 * @Title: addWordList
	 * @param wordList
	 * @author xiaoa
	 */
	public void addWordList(List<String> wordList){
		dic.addWords(wordList);
	}
	
	/**
	 * 分析出词
	 * @Title: analyzerWord
	 * @param str
	 * @return
	 * @throws Exception
	 * @author xiaoa
	 */
	public List<String>  analyzerWord(String str)throws Exception{
		if (str == null || str.isEmpty()){
			return new ArrayList<>();
		}
		
		List<String>  wordList = new ArrayList<>();
		
		try(IKAnalyzer myIkAnalyzer = new IKAnalyzer(true ,Arrays.asList(new CJKSegmenter(dic)) , config , dic);){
			
			TokenStream  ts =  myIkAnalyzer.tokenStream("name", str);
			
			final CharTermAttribute term =  ts.addAttribute( CharTermAttribute.class);
			final TypeAttribute type =  ts.addAttribute( TypeAttribute.class);
			ts.reset();
			while (ts.incrementToken()) {
				
				if (!type.type().equals("CN_WORD") ){
					continue;
				}
				
				wordList.add(term.toString());
				
			}
			ts.end();
		}
		
		
		
		return wordList;
	}
	

	

}
